package com.openlogic.logic.controller.logic;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Delete;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.annotation.Path;
import org.noear.solon.annotation.Post;
import org.noear.solon.annotation.Put;
import org.noear.solon.auth.annotation.AuthPermissions;
import org.noear.solon.core.handle.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.paginate.Page;
import com.openlogic.api.logic.entity.RuleModelDeploy;
import com.openlogic.common.core.enums.BusinessType;
import com.openlogic.common.core.web.controller.BaseController;
import com.openlogic.common.core.web.domain.PageData;
import com.openlogic.common.datasource.annotation.QzLog;
import com.openlogic.common.logic.annotation.RuleLog;
import com.openlogic.common.logic.constants.RuleTypeConstants;
import com.openlogic.common.logic.decision.scorecard.model.ScoreCardTableResultVo;
import com.openlogic.logic.service.logic.RuleDecisionScoreCardService;
import com.openlogic.logic.service.logic.RuleModelDeployService;

import io.swagger.annotations.ApiOperation;

/**
* @ClassName: RuleDecisionScoreCardController
* @Description: 规则评分卡Controller
* @author weiyongpeng
* @date 2024年7月14日 上午10:42:13
 */
@ApiOperation(value = "评分卡功能管理API")
@Controller
@Mapping("rule/model/decisionScoreCard")
public class RuleDecisionScoreCardController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(RuleDecisionScoreCardController.class);
	
	@Resource
	private RuleModelDeployService ruleModelDeployService;
	
	@Resource
	private RuleDecisionScoreCardService ruleDecisionScoreCardService;
	
	/**
	* 描述：根据参数查询评分卡列表
	* @Title: listDecisionTreeByParams
	* @param params
	* @return
	* @author weiyongpeng
	* @date  2024年7月18日 上午11:28:08
	 */
	@ApiOperation(value = "查询评分卡列表")
	@Get
	@Mapping("listDecisionScoreCardByParams")
	@AuthPermissions("rule:model:list")
	@QzLog(title = "查询评分卡列表", businessType = BusinessType.LIST)
	public PageData<RuleModelDeploy> listDecisionTreeByParams(Page<RuleModelDeploy> page, @Param Map<String, Object> params) {
		startPage(page);
		List<RuleModelDeploy> list = this.ruleModelDeployService.findRuleDeployByParams(params);
		return getPageData(list);
	}
	
	/**
	* 描述：保存评分卡模型
	* @Title: save
	* @param ruleModelVersion
	* @param ruleModelName
	* @param ruleRawValue
	* @param ruleModelValue
	* @param id
	* @param remark
	* @return
	* @author weiyongpeng
	* @date  2024年8月3日 下午7:16:26
	 */
	@ApiOperation(value = "评分卡模型保存|修改|新增版本")
	@Post
	@Mapping(value = "save")
	@AuthPermissions("rule:model:add")
	@QzLog(title = "评分卡模型保存", businessType = BusinessType.INSERT)
	public Result<String> save(
			@Param(value="ruleModelVersion",required = false) String ruleModelVersion,
			@Param(value="ruleModelName",required = false) String ruleModelName,
			@Param(value="ruleModelValue",required = false) String ruleModelValue,
			@Param(value="ruleRawValue",required = false) String ruleRawValue,
			@Param(value="id",required = false) String id,
			@Param(value="remark",required = false) String remark
	 ) {
		try {
			RuleModelDeploy ruleModelDeploy = new RuleModelDeploy();
			if(id != null && StringUtils.isNotBlank(id)) {
				ruleModelDeploy.setId(id);
			}if(ruleModelVersion != null && StringUtils.isNotBlank(ruleModelVersion)) {
				ruleModelDeploy.setRuleModelVersion(ruleModelVersion);
			}if(ruleModelName != null && StringUtils.isNotBlank(ruleModelName)) {
				ruleModelDeploy.setRuleModelName(ruleModelName);
			}if(ruleModelValue != null && StringUtils.isNotBlank(ruleModelValue)) {
				ruleModelDeploy.setRuleModelValue(ruleModelValue);
			}if(remark != null && StringUtils.isNotBlank(remark)) {
				ruleModelDeploy.setRemark(remark);
			}if(ruleRawValue != null && StringUtils.isNotBlank(ruleRawValue)) {
				ruleModelDeploy.setRuleRawValue(ruleRawValue);
			}
			// 保存规则信息
			ruleDecisionScoreCardService.save(ruleModelDeploy);
			return Result.succeed();
		} catch (Exception e) {
			logger.error("添加错误：{}", e);
			return Result.failure("添加错误，请联系开发人员检查");
		}
	}
	
	/**
	* 描述：修改评分卡状态
	* @Title: updateStatus
	* @param ruleModelDeploy
	* @return
	* @author weiyongpeng
	* @date  2024年7月16日 上午11:24:49
	 */
	@ApiOperation(value = "评分卡状态修改")
	@Put
	@Mapping("updateStatus")
	@AuthPermissions("rule:model:update")
	@QzLog(title = "评分卡状态修改", businessType = BusinessType.UPDATE)
	public Result<String> updateStatus(@Body RuleModelDeploy ruleModelDeploy) {
		boolean updateFlag = ruleDecisionScoreCardService.updateStatus(ruleModelDeploy);
		if (updateFlag) {
			return Result.succeed("评分卡状态修改成功");
		}
		return Result.failure("评分卡修改,暂无修改数据");
	}
	
	/**
	* 描述：删除评分卡
	* @Title: delete
	* @param ruleModelKey
	* @return
	* @author weiyongpeng
	* @date  2024年7月16日 上午11:24:49
	 */
	@ApiOperation(value = "评分卡模型删除")
	@Delete
	@Mapping("delete/{id}")
	@AuthPermissions("rule:model:delete")
	@QzLog(title = "评分卡删除", businessType = BusinessType.DELETE)
	public Result<String> delete(@Path("id") String id) {
		boolean deleteFlag = ruleDecisionScoreCardService.delete(id);
		if (deleteFlag) {
			return Result.succeed("评分卡删除成功");
		}
		return Result.failure("评分卡删除,暂无删除数据");
		
	}
	
	/**
	* 描述：评分卡debug调试
	* @Title: debug
	* @param dataInfo
	* @param jsonStr
	* @param ruleId
	* @return
	* @author weiyongpeng
	* @date  2024年9月27日 上午11:00:11
	 */
	@ApiOperation(value = "评分卡debug调试")
	@Post
	@Mapping(value = "debug")
	@AuthPermissions("rule:model:list")
	@RuleLog(ruleType = RuleTypeConstants.scoreCard)
	public Result<ScoreCardTableResultVo> debug(@Param("datas") String dataInfo,
							@Param("decisionScoreCard") String scoreCard,
							@Param(value="ruleId") String ruleId,
							@Param(value="ruleName") String ruleName,
							@Param("rawValue") String rawValue) throws Exception{
		ScoreCardTableResultVo resultVo = ruleDecisionScoreCardService.debug(dataInfo,scoreCard);
		return Result.succeed(resultVo);
	}
	
	/**
	* 描述：评分卡执行调用
	* @Title: execuate
	* @param datas
	* @param id
	* @param operateNo
	* @return
	* @author weiyongpeng
	* @date  2024年10月24日 下午6:52:43
	 */
	@Get
	@Mapping("execuate")
	public Result<String> execuate(@Param("datas") String datas, @Param("id") @NotNull String id, @Param("operateNo") String operateNo) {
		Map<String,Object> resultMap = new HashMap<>();
		String caclKey = "caclRes";
		try {
			// 执行规则
			ScoreCardTableResultVo resultVo = ruleDecisionScoreCardService.execuateRule(datas,id,operateNo);
			if (Optional.ofNullable(resultVo).isPresent() && Optional.ofNullable(resultVo.getResult()).isPresent()) {
				String caclRes = resultVo.getResult().toString().split("=")[1];
				resultMap.put(caclKey, caclRes);
			}else {
				resultMap.put(caclKey, "0");
			}
		} catch (Exception e) {
			logger.error("决策执行错误：{}", e);
			resultMap.put(caclKey, "0");
		}
		return Result.succeed(new JSONObject(resultMap).toString());
	}
}
